package es_ser

import (
	"context"
	"github.com/PuerkitoBio/goquery"
	"github.com/olivere/elastic/v7"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"pkg/mod/github.com/russross/blackfriday"
	"strings"
)

type SearchData struct {
	Key   string `json:"key"`   //文章关联的id
	Body  string `json:"body"`  //正文
	Slug  string `json:"slug"`  //跳转地址
	Title string `json:"title"` //文章标题
}

// AsyncArticleByFullText 同步文章数据到全文搜索
func AsyncArticleByFullText(id, title, content string) {
	indexList := GetSearchIndexDataByContent(id, title, content)

	bulk := global.EsClient.Bulk()
	for _, indexData := range indexList {
		//批量添加
		req := elastic.NewBulkIndexRequest().Index(models.FullTextModel{}.Index()).Doc(indexData)
		bulk.Add(req)
	}
	result, err := bulk.Do(context.Background())
	if err != nil {
		global.Log.Error(err.Error())
		return
	}
	global.Log.Infof("%s 添加成功,共 %d 条", title, len(result.Succeeded()))
}

// DeleteFullTextByID 删除文章数据
func DeleteFullTextByID(id string) {
	boolSearch := elastic.NewTermQuery("key", id)
	res, _ := global.EsClient.
		DeleteByQuery().
		Index(models.FullTextModel{}.Index()).
		Query(boolSearch).
		Do(context.Background())
	global.Log.Infof("成功删除%d条记录", res.Deleted)
}

func GetSearchIndexDataByContent(id, title, content string) (SearchDataList []SearchData) {
	dataList := strings.Split(content, "\n")
	var isCode = false
	var headList, bodyList []string
	var body string
	headList = append(headList, getHeader(title))
	for _, s := range dataList {
		//判断是否是代码块
		if strings.HasPrefix(s, "```") {
			isCode = !isCode
		}
		//判断是否是标题
		if strings.HasPrefix(s, "#") && !isCode {
			headList = append(headList, getHeader(s))
			//if strings.TrimSpace(body) != "" {
			bodyList = append(bodyList, getBody(body))
			//}
			body = ""
			continue
		}
		body += s
	}
	bodyList = append(bodyList, getBody(body))
	ln := len(headList)
	for i := 0; i < ln; i++ {
		SearchDataList = append(SearchDataList, SearchData{
			Title: headList[i],
			Body:  bodyList[i],
			Slug:  id + getSlug(headList[i]),
			Key:   id,
		})
	}
	return SearchDataList
}
func getHeader(head string) string {
	head = strings.ReplaceAll(head, "#", "")
	head = strings.ReplaceAll(head, " ", "")
	return head
}
func getBody(body string) string {
	unsafe := blackfriday.MarkdownCommon([]byte(body))
	//是不是有script标签
	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(string(unsafe)))
	return doc.Text()
}
func getSlug(slug string) string {
	return "#" + slug
}
